//
//  FYComposeViewController.swift
//  Weibo
//
//  Created by 冯毅 on 16/8/16.
//  Copyright © 2016年 冯毅. All rights reserved.
//

import UIKit
import SVProgressHUD
class FYComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    //  MARK: -懒加载控件
    private lazy var rightButton: UIButton = {
        let button = UIButton()
        
        //  添加点击事件
        button.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        button.setTitle("发送", forState: .Normal)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //  设置不同状态的文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
        
        //设置不同状态下的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        
        //  设置大小
        button.size = CGSize(width: 45, height: 30)
        return button
    }()
    
    //  标题视图
    private lazy var titleView: UILabel = {
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGrayColor())
        if let name = FYUserAccountViewModel.sharedUserAccount.userAccount?.name {
            let result = "发微博\n\(name)"
            //  获取名称的range
            let range = (result as NSString).rangeOfString(name)
            
            let attribuedStr = NSMutableAttributedString(string: result)
            
            //  添加富文本属性
            attribuedStr.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(14)],range:range)
            
            label.attributedText = attribuedStr
        } else {
            label.text = "发微博"
        }
        //  多行显示
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        
        return label
    }()
    
    //  发微博视图
    private lazy var textView: FYComposeTextView = {
        let view = FYComposeTextView()
        //  设置代理
        view.delegate = self
        view.placeHolder = "请输入微博内容"
        view.font = UIFont.systemFontOfSize(16)
        //  垂直方向开启拖动
        view.alwaysBounceVertical = true
        return view
    }()
    
    //  toolbar
    private lazy var toolBar: FYComposeToolBar = {
        let composeToolbar = FYComposeToolBar(frame: CGRectZero)
        return composeToolbar
    }()
    
    //  配图
    private lazy var pictureView: FYComposePictureView = {
        let picView = FYComposePictureView()
        return picView
    }()
    
    //  添加控件设置约束
    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        //  监听键盘改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardFrameChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        setupNavUI()
        
        view.addSubview(textView)
        textView.addSubview(pictureView)
        view.addSubview(toolBar)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView.snp_width).offset(-10)
            make.height.equalTo(textView.snp_width).offset(-10)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(35)
            
        }
        //  分析处理有循环引用,使用[weak self]
        toolBar.didSelecterToolBarButtonClouse = { [weak self] (type:FYComposeToolBarButtonType) in
            //  根据点击按钮的枚举值进行判断
            switch type {
            case .Picture:
                print("图片")
                self?.didSelectedPicture()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
                print("表情")
            case .Add:
                print("加号")
                
            }
        
        }
    }
    
    private func setupNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target:self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    @objc private func keyboardFrameChange(noti:NSNotification) {
        
        let keyBoardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyBoardFrame.origin.y - self.view.height)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func cancelAction() {
        self.view.endEditing(true)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendAction() {
        let status = textView.text!
        let accessToken = FYUserAccountViewModel.sharedUserAccount.accessToken!
        FYNetworkTools.sharedTools.update(accessToken, status: status) { (response, error) -> () in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("网络异常发送失败")
                print(error)
                return
            }
            SVProgressHUD.showSuccessWithStatus("发送成功")
        }
    }
}

extension FYComposeViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func didSelectedPicture() {
        let picCtr = UIImagePickerController()
        picCtr.delegate = self
        
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            picCtr.sourceType = .Camera
            
        } else {
            picCtr.sourceType = .PhotoLibrary
        }
        if UIImagePickerController.isCameraDeviceAvailable(.Front){
            print("前置摄像头")
            
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear){
            print("后置摄像头")
        } else {
            print("没有摄像头")
        }
        
        presentViewController(picCtr, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        pictureView.addImage(image)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

extension FYComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        self.view.endEditing(true)
        
    }
}
